const router = require('koa-router')();
const { sequelize } = require('../common/dbs')

var Sequelize = require('sequelize')
var Op = Sequelize.Op;

const userinfoModel = require("../models/userinfo")
const userinfo = userinfoModel(sequelize);
var md5 = require('md5-node');
let jwt = require('jsonwebtoken');


// 注册
router.post('/register', async (ctx) => {
    try {
        ctx
            .validateBody("email")
            .required("邮箱不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("pwd")
            .required("密码不能为空")
            .isString()
            .trim()

        console.log(ctx.request.body)
        let reqBody = ctx.request.body;
        let requestData = null
        let salt = getuuid(6)
        let pwd = md5(reqBody.pwd + salt)

        let b = {
            id: getuuid(),
            user_name: '游客',
            user_email: reqBody.email,
            role_ids: 8, //默认角色
            user_pwd: pwd,
            user_pwd_salt: salt //加盐随机生成
        }
        // 新增
        requestData = await userinfo.create(b)
        if (requestData) {
            ctx.success(null,'注册成功')
        } else {
            ctx.fail(0, '评论失败')
        }

    } catch (err) {
        ctx.fail(0, err && err.message)
    }
})
/**
 * 登录
 * */
 router.post('/login', async (ctx) => {
    try {
        ctx
            .validateBody("email")
            .required("邮箱不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("password")
            .required("密码不能为空")
            .isString()
            .trim()
        let reqBody = ctx.request.body;


        // 查询账号是否存在
        let cardData = await userinfo.findOne(
            {
                where: {
                    user_email: reqBody.email
                }
            }
        );
        if (!cardData) {
            ctx.fail(0, '登录失败，该账号不存在')
            return
        }

        // 加盐
        if (md5(reqBody.password + cardData.user_pwd_salt) === cardData.user_pwd) {
            console.log(cardData)
            //  "uid": cardData.uid,
            let payload = {
                "userid": cardData.id,
                "roleid": cardData.role_ids
            }
            let newToken = jwt.sign(payload, 'itliuyang', { expiresIn: 60000 });

            ctx.success({ access_token: newToken },'登录成功')

        } else {
            ctx.fail(0, '登录失败，账号或者密码错误')
        }
    } catch (err) {
        ctx.fail(0, err)
    }
})
/**
 * 修改密码
 * */
 router.post('/updatePassword', async (ctx) => {
    try {
        ctx
            .validateBody("password")
            .required("密码不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("newPassword")
            .required("新密码不能为空")
            .isString()
            .trim()


        let reqBody = ctx.request.body;
        let requestData = null
        // 对比密码
        if (reqBody.confirmPassword !== reqBody.newPassword) {
            ctx.fail(0, '前后密码输入不一致')
            return
        }
        let id = getUserId(ctx)

        // 校验原密码是否正确
        let infoData = await userinfo.findOne(
            {
                where: {
                    id: id
                },
                // attributes: ['id', 'user_email','user_name'],
            }
        );

        if (md5(reqBody.password + infoData.user_pwd_salt) !== infoData.user_pwd) {
            ctx.fail(0, '密码错误')
            return
        }

        let salt = getuuid(6)
        let pwd = md5(reqBody.newPassword + salt)
        let b = {
            user_pwd: pwd,
            user_pwd_salt: salt //加盐随机生成
        }
        if (id) {
            // 编辑
            requestData = await userinfo.update(b, {
                where: {
                    id: id
                }
            })

            if (requestData[0] > 0) {
                ctx.success(null,'修改成功')
            } else {
                ctx.fail(0, '修改失败,请重新稍后再试')
            }

        } else {
            ctx.fail(0, '修改失败,请重新尝试重新登录再试')
        }


    } catch (err) {
        ctx.fail(0, err && err.message)
    }
})


/**
 * 查个人信息
 * */
 router.get('/info', async (ctx) => {
    try {
        let reqBody = ctx.request.body;
        console.log('===', getUserId(ctx))
        let cardData = await userinfo.findOne(
            {
                where: {
                    id: getUserId(ctx)
                },
                attributes: ['id', 'user_email','user_name','created_at','avatar'],
            }
        );

        if (cardData) {
            ctx.success(cardData)
        } else {
            ctx.fail(0, '查询失败')
        }

    } catch (err) {
        ctx.fail(0, err)
    }
})






/**
 * 编辑或者添加
 * */

router.post('/editOrAdd', async (ctx) => {
    try {
        ctx
            .validateBody("user_email")
            .required("邮箱不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body;
        let requestData = null
        let msgType = '添加'

        let salt = getuuid(6)
        let pwd = md5(reqBody.pwd + salt)
        let b = {
            id: getuuid(),
            user_name: reqBody.user_name || '游客',
            user_email: reqBody.user_email,
            role_ids: reqBody.role_ids ? reqBody.role_ids.toString() : '',
            user_pwd: pwd,
            user_pwd_salt: salt //加盐随机生成
        }

        if (reqBody.id) {
            delete b.id
            // 编辑
            requestData = await userinfo.update(b, {
                where: {
                    id: reqBody.id
                }
            })
            msgType = '修改'
        } else {
            // 新增
            requestData = await userinfo.create(b)
        }
        if (requestData) {
            ctx.success(msgType + '成功')
        } else {
            ctx.fail(0, msgType + '失败')
        }

    } catch (err) {
        ctx.fail(0, err && err.message)
    }
})

/**
 * 重置密码
 * */

router.post('/resetPwd', async (ctx) => {
    try {
        ctx
            .validateBody("id")
            .required("id不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body;
        let requestData = null

        let salt = getuuid(6)
        let pwd = md5('123456' + salt)
        let b = {
            user_pwd: pwd,
            user_pwd_salt: salt //加盐随机生成
        }
        let id = getUserId(ctx)
        if (id) {
            // 编辑
            requestData = await userinfo.update(b, {
                where: {
                    id: id
                }
            })
            if (requestData[0] > 0) {
                ctx.success('')
            } else {
                ctx.fail(0, '重置失败,请重新稍后再试')
            }

        } else {
            ctx.fail(0, '重置失败,请重新尝试重新登录再试')
        }

    } catch (err) {
        ctx.fail(0, err && err.message)
    }
})



// 登录
// router.post('/login', async (ctx) => {
//     try {
//         let reqBody = ctx.request.body;

//         console.log(reqBody)
//         ctx.success({ access_token: '30c94f4b-5094-46ab-b463-09e88be0bca2' })
//     } catch (err) {
//         ctx.fail(0, err)
//     }
// })


/**
 * 退出
 * */
router.post('/loginOut', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        ctx.success(null)
    } catch (err) {
        ctx.fail(0, err)
    }
})


function getUserId(ctx) {
    let token = ctx.request.headers["authorization"]
    try {
        console.log(token)
        if (token) {
            const tokenItem = jwt.verify(token.split("Bearer ")[1], 'itliuyang')
            console.log(tokenItem)
            if (tokenItem) {
                return tokenItem.userid
            }
        }
    } catch (error) {
        ctx.fail(0, error)
    }

    return ''
}






/**
 * 详情
 * */

router.get('/detail', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        if (!reqQuery.id) {
            ctx.fail(0, 'id不能为空')
        }
        let cardData = await userinfo.findOne(
            {
                where: {
                    id: reqQuery.id
                },
            }
        );

        if (cardData) {
            ctx.success(cardData)
        } else {
            ctx.fail(0, '内容已删除,或者不存在')
        }
    } catch (err) {
        ctx.fail(0, err)
    }
})


// 查询列表
router.get('/pageList', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        let reData = await userinfo.findAndCountAll(
            {
                where: {
                    user_name: {
                        [Op.like]: `%${reqQuery.user_name}%`
                    },
                    user_email: {
                        [Op.like]: `%${reqQuery.user_email}%`
                    }
                },
                attributes: ['id', 'user_email', 'user_name', 'created_at', 'role_ids'],
                order: [  //排序 DESC ASC
                    ['created_at', 'DESC']
                ],
                limit: reqQuery.limit ? parseInt(reqQuery.limit) : 10,
                offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0
            }
        );
        ctx.success(reData)
    } catch (err) {
        ctx.fail(0, err)
    }
})
// 删除
router.delete('/del/:id', async (ctx) => {
    try {
        if (!ctx.params.id) {
            ctx.fail(0, 'id不能为空')
        }
        let requestData = await userinfo.destroy({
            where: {
                id: ctx.params.id
            }
        })
        if (requestData > 0) {
            ctx.success('删除成功')
        } else {
            ctx.fail(0, '内容已删除,或者不存在')
        }
    } catch (err) {
        ctx.fail(0, err)
    }
})

module.exports = router.routes();




function getuuid(numer = 32) {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (var i = 0; i < numer; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    // s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid;
}
